package renguanyu.app.tools.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

public class MavenDependenciesToTargetController {

	@FXML
	TextArea mavenDependenciesPaths;
	@FXML
	TextField targetPath;

	@FXML
	public void copyMavenDependenciesTarget() throws IOException {
		String target = "D:/tmp/";
		if (!targetPath.getText().isEmpty()) {
			target = targetPath.getText();
			if (!target.endsWith("/")) {
				target = target + "/";
			}
		}
		String[] mavenJarPathArray = mavenDependenciesPaths.getText().split("\n");
		List<String> filePaths = new ArrayList<>();
		for (String mavenJarPath : mavenJarPathArray) {
			mavenJarPath = mavenJarPath.replace("\\", "/");
			filePaths.add(mavenJarPath);
		}
		for (String tmpStr : filePaths) {
			String strArr[] = tmpStr.split("/");
			String fileName = strArr[(strArr.length - 1)];
			copyFile(tmpStr, target + fileName, true);
		}
	}

	private static void copyFile(String srcFilename, String destFilename, boolean overwrite) throws IOException {
		File srcFile = new File(srcFilename);
		if (!srcFile.exists()) {
			throw new FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath());
		}
		if (!srcFile.canRead()) {
			throw new IOException("Cannot read the source file: " + srcFile.getAbsolutePath());
		}
		File destFile = new File(destFilename);
		if (overwrite == false) {
			if (destFile.exists()) {
				return;
			}
		} else {
			if (destFile.exists()) {
				if (!destFile.canWrite()) {
					throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
				}
			} else {
				if (!destFile.createNewFile()) {
					throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
				}
			}
		}
		BufferedInputStream inputStream = null;
		BufferedOutputStream outputStream = null;
		byte[] block = new byte[1024];
		try {
			inputStream = new BufferedInputStream(new FileInputStream(srcFile));
			outputStream = new BufferedOutputStream(new FileOutputStream(destFile));
			while (true) {
				int readLength = inputStream.read(block);
				if (readLength == -1) {
					break;
				}
				outputStream.write(block, 0, readLength);
			}
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
			if (outputStream != null) {
				outputStream.close();
			}
		}
	}

}
